import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import Cell from './Cell';
import AddCourseModal from './AddCourseModal';
import Slider from "react-slick"; // 引入轮播组件
import "slick-carousel/slick/slick.css"; 
import "slick-carousel/slick/slick-theme.css";
import { useNavigate } from 'react-router-dom';

const BannerContainer = styled.div`
  display: flex;
  flex-wrap: wrap; /* 自动换行 */
  width: 100%; /* 确保与表格等宽 */
  max-width: 1200px; /* 与表格的 max-width 保持一致 */
  margin: 0 auto; /* 居中 */
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 0 10px;
  height: auto; /* 自动适应高度 */
`;

const BannerSection = styled.div`
  flex: 1; /* 平分宽度 */
  margin: 5px; /* 添加间距 */
  max-width: 48%; /* 最大宽度为 48% */
`;


const BannerImage = styled.img`
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例 */
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
`;



// 添加按钮 HTML
const ButtonContainer = styled.div`
  text-align: center;
  margin: 20px 0;
`;

const Button = styled.button`
  padding: 10px 20px;
  background-color: #4A90E2;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
`;


// 行程表的样式：每一天占一列
const TableWrapper = styled.div`
  width: 100%;
  max-width: 1200px; /* 限制最大宽度，防止溢出 */
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(7, 1fr);  /* 每列表示一天 */
  grid-template-rows: auto repeat(12, 1fr);   /* 第一行显示星期和日期，剩下的12行表示时间段 */
  gap: 1px;
  background: linear-gradient(145deg, #e8f7fc, #ffffff);  /* 渐变背景 */
  border-radius: 10px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  padding: 10px;
`;

const Title = styled.h1`
  text-align: center;
  font-size: 28px;
  color: #4A90E2;
  margin-top: 30px;
  font-family: 'Roboto', sans-serif;
`;

const Subtitle = styled.p`
  text-align: center;
  font-size: 16px;
  color: #4A90E2;
  margin-top: 10px;
  font-family: 'Roboto', sans-serif;
`;

const WeekNavigation = styled.div`
  display: flex;
  justify-content: space-between;
  margin: 20px;
`;

const ArrowButton = styled.button`
  background-color: #4A90E2;
  color: white;
  border: none;
  padding: 10px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 5px;

  &:hover {
    background-color: #357ABD;
  }
`;

const HeaderCell = styled.div`
  text-align: center;
  font-size: 14px;
  color: #4A90E2;
  padding: 10px;
  font-weight: bold;
  background-color: ${(props) => (props.isToday ? '#d3e5ff' : '#f0f0f0')}; /* 高亮今天 */
  border: 1px solid #ddd;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: ${(props) => (props.isToday ? '0 0 10px rgba(0, 0, 255, 0.3)' : 'none')}; /* 添加阴影 */
`;


const FooterContainer = styled.footer`
  margin-top: 20px; /* 增加顶部间距 */
  background-color: #f8f9fa;
  color: #6c757d;
  text-align: center;
  padding: 10px 0;
  position: fixed;
  bottom: 0;
  width: 100%;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  font-family: 'Roboto', sans-serif;
`;

const CourseTable = () => {
  const [courses, setCourses] = useState([]);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedTime, setSelectedTime] = useState(null);
  const [selectedDay, setSelectedDay] = useState(null);
  const [selectedCourse, setSelectedCourse] = useState(null);
  const [currentWeekStart, setCurrentWeekStart] = useState(getStartOfWeek(new Date())); // 当前周的开始日期
  const settings = {
    dots: true, // 显示点导航
    infinite: true, // 无限滚动
    speed: 500, // 动画速度
    slidesToShow: 1, // 每次展示的幻灯片数量
    slidesToScroll: 1, // 每次滚动的幻灯片数量
    autoplay: true, // 自动播放
    autoplaySpeed: 3000, // 每3秒自动切换
  };

  const today = new Date().getDay(); // 获取今天是星期几

  // 获取当前周的日期数组
  const getWeekDates = (startOfWeek) => {
    let dates = [];
    for (let i = 0; i < 7; i++) {
      const date = new Date(startOfWeek);
      date.setDate(startOfWeek.getDate() + i);
      dates.push(date);
    }
    return dates;
  };

  // 获取周的开始日期（假设每周从星期一开始）
  function getStartOfWeek(date) {
    const startOfWeek = new Date(date);
    const day = startOfWeek.getDay(); // 获取今天是星期几
    const diff = startOfWeek.getDate() - day + (day === 1 ? -7 : 0); // 计算距离周一的天数
    startOfWeek.setDate(diff);
    startOfWeek.setHours(0, 0, 0, 0); // 设置为当天 00:00:00
    return startOfWeek;
  }

  const handleWeekChange = (direction) => {
    const newStart = new Date(currentWeekStart);
    newStart.setDate(currentWeekStart.getDate() + direction * 7); // 切换到下一周或上一周
    const newWeekStart = getStartOfWeek(newStart);
    setCurrentWeekStart(newWeekStart);
  
    // 更新对应周的行程数据
    fetchCourses(newWeekStart);
  };
  
  const getWeekCourses = () => {
    const weekDates = getWeekDates(currentWeekStart);
    return courses.filter((course) => {
      const courseDate = new Date(course.date); // 假设后端返回的行程数据中有 `date` 字段
      return weekDates.some(
        (weekDate) => courseDate.toDateString() === weekDate.toDateString()
      );
    });
  };
  
  const weekCourses = getWeekCourses();

  // 自动滚动到今天的行
  useEffect(() => {
    const todayCell = document.getElementById(`day-${today}`);
    if (todayCell) {
      todayCell.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }, [today]);

  // 获取日期
  const getDate = (dayIndex) => {
    const weekDates = getWeekDates(currentWeekStart);
    return weekDates[dayIndex].toLocaleDateString(); // 格式化为日期（如：2025/1/6）
  };

  const fetchCourses = async (weekStart) => {
    try {
      const response = await axios.get('http://localhost:5000/api/courses', {
        params: { weekStart: weekStart.toISOString().split('T')[0] }, // 传递周的开始日期
      });
  
      // 按时间排序
      const sortedCourses = response.data.sort((a, b) => a.time - b.time);
      setCourses(sortedCourses);
      setLoading(false);
    } catch (error) {
      console.error('Error fetching courses:', error);
      setLoading(false);
    }
  };
  

  // 更新课程数据
  const handleAddCourse = async (name, startTime, day, instructor) => {
    try {
      const response = await axios.post('http://localhost:5000/api/courses', {
        name,
        time: startTime,  // 传递开始时间
        day,
        instructor,
      });

      setCourses((prevCourses) => {
        const updatedCourses = prevCourses.filter(
          (c) => c.time !== startTime || c.day !== day
        );
        updatedCourses.push(response.data);
        updatedCourses.sort((a, b) => a.time - b.time);
          /*{
          const timeA = a.time instanceof Date ? a.time.toString() : a.time + '';  // 转换为字符串
          const timeB = b.time instanceof Date ? b.time.toString() : b.time + '';  // 转换为字符串
          return timeA.localeCompare(timeB);  // 按开始时间排序
           });*/
        return updatedCourses;
      });
      setIsModalOpen(false);
    } catch (error) {
      console.error('Error adding course:', error);
    }
  };

// 删除课程
const handleDeleteCourse = async (courseId) => {
  try {
    // 调用后端删除接口
    await axios.delete(`http://localhost:5000/api/courses/${courseId}`);
    // 更新本地的课程状态
    setCourses((prevCourses) =>
      prevCourses.filter((course) => course.id !== courseId)
    );
    console.log('课程删除成功');
  } catch (error) {
    console.error('删除课程失败:', error);
  }
};


  useEffect(() => {
    fetchCourses();
    console.log('Fetching courses...');
    axios
      .get('http://localhost:5000/api/courses')
      .then((response) => {
        setCourses(response.data);
        setLoading(false); // 确保在这里设置 loading 为 false
      })
      .catch((error) => {
        console.error('Error fetching courses:', error);
        setLoading(false); // 这里也是需要设置 loading 为 false
      });
  }, []);

  return (
    <div>
      {/* 左右两边轮播图 */}
      <BannerContainer>
        {/* 左侧轮播图 */}
        <BannerSection>
          <Slider {...settings}>
            {['/time4.jpg', '/time3.jpg', '/time7.jpg', '/time6.jpg'].map((imageSrc, index) => (
              <BannerImage key={`left-${index}`} src={imageSrc} />
            ))}
          </Slider>
        </BannerSection>

        {/* 右侧轮播图 */}
        <BannerSection>
          <Slider {...settings}>
            {['/time5.jpg', '/time1.jpg', '/time2.jpg'].map((imageSrc, index) => (
              <BannerImage key={`right-${index}`} src={imageSrc} />
            ))}
          </Slider>
        </BannerSection>
      </BannerContainer>

      {/* 课程表内容 */}
      <Title>我的行程表</Title>
      <Subtitle>今天是星期{['日', '一', '二', '三', '四', '五', '六'][today]}</Subtitle>

      {/* 左右箭头切换上一周或下一周 */}
      <WeekNavigation>
        <ArrowButton onClick={() => handleWeekChange(-1)}>上一周</ArrowButton>
        <ArrowButton onClick={() => handleWeekChange(1)}>下一周</ArrowButton>
      </WeekNavigation>

      <TableWrapper>
        {/* 第一行显示星期和日期 */}
        {['日', '一', '二', '三', '四', '五', '六'].map((day, index) => (
          <HeaderCell key={index} isToday={index === today}> {/* 传递 isToday prop 来改变背景颜色 */}
            <span>{day}</span>
            <span>{getDate(index)}</span>
          </HeaderCell>
        ))}

        {/* 遍历时间段（12个行）和一周的天数（7列） */}
        {Array.from({ length: 12 }).map((_, timeIndex) =>
          Array.from({ length: 7 }).map((_, dayIndex) => {
            const course = courses.find(
              (c) => c.time === timeIndex && c.day === dayIndex
            );
            return (
              <Cell
                key={`${timeIndex}-${dayIndex}`}
                time={timeIndex}
                day={dayIndex}
                course={course}
                onClick={() => {
                  setSelectedTime(timeIndex);
                  setSelectedDay(dayIndex);
                  setSelectedCourse(course);
                  setIsModalOpen(true);
                }}
                id={`day-${dayIndex}`} // 添加ID方便滚动
                onDelete={handleDeleteCourse} // 传递删除处理函数
              />
            );
          })
        )}
      </TableWrapper>

      {/* 弹出行程修改的 Modal */}
      {isModalOpen && (
        <AddCourseModal
          time={selectedTime} // 传递选中的时间
          day={selectedDay} // 传递选中的星期
          course={selectedCourse}
          onSave={(name, instructor) =>
            handleAddCourse(name, selectedTime, selectedDay, instructor)
          } // 保存行程
          closeModal={() => setIsModalOpen(false)} // 关闭模态框
        />
      )}

      {/* 添加 Footer 容器 */}
      <FooterContainer>
        © 2025 行云纪行（行程规划记录平台）. 保留所有权利。
      </FooterContainer>
    </div>
  );
};

export default CourseTable;
